// ignore_for_file: constant_identifier_names

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:tiktokadult/hj_model/video_model.dart';
import 'package:tiktokadult/hj_page/short_video/short_video_logic.dart';
import 'package:tiktokadult/hj_page/short_video/view/short_progress_widget.dart';
import 'package:tiktokadult/hj_page/short_video/view/short_video_ad_widget.dart';
import 'package:tiktokadult/hj_page/short_video/view/short_video_menu.dart';
import 'package:tiktokadult/hj_page/short_video/view/short_video_player.dart';
import 'package:tiktokadult/tools_base/loading/l_error_widget.dart';
import 'package:tiktokadult/tools_base/loading/loading_center_widget.dart';

import '../../hj_utils/event_tracking_manager.dart';

/// SECOND 短视频只有一个视频(入参视频需要通过视频详情接口获取权限)，需要加载推荐列表数据；
/// SECONDList 传过来的不止一个视频，不需要加载推荐列表数据（列表视频数据，都需要视频详情接口获取权限）；
enum VideoListType { FOLLOW, RECOMMEND, SECOND, Newest }

class ShortVideoPage extends StatefulWidget {
  final VideoListType type;
  final TabController? superTabController;
  final int? tabIndex; //
  final List<VideoModel>? videoList;
  final int pageIndex;

  const ShortVideoPage({
    super.key,
    this.type = VideoListType.SECOND,
    this.superTabController,
    this.tabIndex,
    this.videoList,
    this.pageIndex = 0,
  });

  @override
  State<StatefulWidget> createState() {
    return _ShortVideoPageState();
  }
}

class _ShortVideoPageState extends State<ShortVideoPage> {
  static int getTagIndex = 0;

  late ShortVideoLogic logic;

  String getxLogicTag = "";

  @override
  void initState() {
    getxLogicTag = "ShortVideoLogic--${getTagIndex++}";
    ShortVideoMenu.addListen(_menuShowListener);
    logic = Get.put(
      ShortVideoLogic(
        fctType: widget.type,
        pageIndex: widget.pageIndex,
        videoList: widget.videoList,
      ),
      tag: getxLogicTag,
    );
    super.initState();
    if (widget.type == VideoListType.FOLLOW) {
      EventTrackingManager.uploadEvent("点击", eventProperties: {"链路": "短视频-关注"});
    }
    widget.superTabController?.addListener(_listerTabIndex);
  }

  void _listerTabIndex() {
    ShortVideoLogic.tabMIndex = widget.superTabController?.index ?? 0;
    if (ShortVideoLogic.tabMIndex == widget.tabIndex) {
      ShortVideoLogic.play();
    } else {
      ShortVideoLogic.pauseAll();
    }
    if (widget.superTabController?.index == widget.tabIndex && logic.videoList?.isEmpty == true) {
      logic.initData();
    }
  }

  void _menuShowListener(bool isShow) {
    logic.isShowMenu.value = isShow;
  }

  @override
  Widget build(BuildContext context) {
    return Material(
      color: Colors.transparent,
      child: Obx(() {
        if (logic.loadCount.value == 0) {
          return const LoadingCenterWidget();
        } else if (logic.videoList?.isNotEmpty != true) {
          return CErrorWidget(
            retryOnTap: () {
              logic.initData();
            },
          );
        } else {
          return Stack(
            fit: StackFit.expand,
            children: [
              RefreshIndicator(
                onRefresh: () => logic.loadData(),
                child: PageView.builder(
                  onPageChanged: (int index) {
                    // if (!ShortVideoMenu.isShow) {
                    //   ShortVideoMenu.isShow = true;
                    //   ShortVideoMenu.notifyListeners();
                    // }
                    logic.onPageChanged(index);
                  },
                  physics: const ClampingScrollPhysics(),
                  controller: logic.pageController,
                  scrollDirection: Axis.vertical,
                  allowImplicitScrolling: true,
                  itemCount: logic.videoList?.length ?? 0,
                  itemBuilder: (context, index) {
                    VideoModel videoInfo = logic.videoList![index];
                    if (videoInfo.isRandomAd()) {
                      return Obx(
                        () => ShortVideoAdWidget(
                          mediaInfo: videoInfo,
                          index: index,
                          isCurrentPage: logic.pageViewIndex.value == index,
                          callback: (ctr) {
                            if (mounted) {
                              logic.setCurController(ctr);
                            }
                          },
                        ),
                      );
                    } else {
                      return Obx(
                        () => ShortVideoPlayer(
                          key: ValueKey(videoInfo.id),
                          index: index,
                          tabIndex: widget.tabIndex,
                          isCurrentPage: logic.pageViewIndex.value == index,
                          videoInfo: videoInfo,
                          fctType: widget.type,
                          superTabController: widget.superTabController,
                          callback: (ctr) {
                            if (mounted) {
                              logic.setCurController(ctr);
                            }
                          },
                        ),
                      );
                    }
                  },
                ),
              ),
              // Positioned(
              //   left: 0,
              //   right: 0,
              //   bottom: 4,
              //   child: Obx(
              //     () => Visibility(
              //       visible: logic.isShowMenu.value,
              //       child: ShortTxtAdWidget(),
              //     ),
              //   ),
              // ),
              Positioned(
                left: 0,
                right: 0,
                bottom: 0,
                child: logic.videoList?.isNotEmpty == true
                    ? Obx(() => Visibility(
                          visible: logic.isShowMenu.value,
                          child: ShortProgressWidget(
                            key: logic.progressKey,
                            padding: EdgeInsets.zero,
                            isShortStyle: true,
                          ),
                        ))
                    : const SizedBox(),
              ),
              Visibility(
                visible: widget.type == VideoListType.SECOND,
                child: Positioned(
                  top: 20,
                  child: Material(
                    color: Colors.transparent,
                    child: Container(
                      padding: EdgeInsets.only(top: 12),
                      child: IconButton(
                        icon: const Icon(
                          Icons.arrow_back_ios,
                          color: Colors.white,
                          shadows: [
                            Shadow(
                              color: Colors.black,
                              offset: Offset(1, 1),
                              blurRadius: 1,
                            ),
                          ],
                        ),
                        onPressed: () => Navigator.pop(context),
                      ),
                    ),
                  ),
                ),
              ),
            ],
          );
        }
      }),
    );
  }

  @override
  void dispose() {
    Get.delete<ShortVideoLogic>(tag: getxLogicTag);
    ShortVideoMenu.removeLister(_menuShowListener);
    widget.superTabController?.removeListener(_listerTabIndex);
    super.dispose();
  }
}
